package main

import (
	hello "04-grpc-metadata/proto"
	"context"
	"fmt"
	"log"
	"net"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/timestamppb"
)

type Server struct {
	hello.UnimplementedHelloServer
}

func (s *Server) SayHello(ctx context.Context, req *hello.HelloReq) (res *hello.HelloRes, err error) {
	res = &hello.HelloRes{
		Data: "200 ok",
		Time: timestamppb.New(time.Now()),
	}

	return
}

func main() {
	// 服务端拦截器
	serverInterceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
		md, ok := metadata.FromIncomingContext(ctx)
		if !ok {
			fmt.Println("no authrization")
			return resp, status.Error(codes.Unauthenticated, "无身份验证")
		}

		// for key, val := range md {
		// 	fmt.Println(key, val)
		// }

		var name, pwd string

		if nameSlice, ok := md["name"]; ok {
			name = nameSlice[0]
		}
		if pwdSlice, ok := md["pwd"]; ok {
			pwd = pwdSlice[0]
		}

		if name != "Bob" || pwd != "123456" {
			fmt.Println("no authrization")
			return resp, status.Error(codes.Unauthenticated, "身份验证出错")
		}

		log.Println("接收到新信息")
		return handler(ctx, req)
	}
	opt := grpc.UnaryInterceptor(serverInterceptor)
	g := grpc.NewServer(opt)
	hello.RegisterHelloServer(g, &Server{})

	listen, err := net.Listen("tcp", "0.0.0.0:3005")
	if err != nil {
		panic(err)
	}
	err = g.Serve(listen)
	if err != nil {
		panic(err)
	}
}
